<script setup>
import {
  auditStudentInternshipMaterialApi,
  checkStudentNineYeInfoApi,
  checkStudentWeeklyApi,
  getApprovedEmploymentMaterialsApi,
  getApprovedMaterialsApi,
  getStudentWeeklyByCounselorApi,
  getStudentWeeklyByCounselorInfoApi,
  uploadStudentInternshipMaterialsApi
} from '@/api/job'
import Form from '@/components/User/Form.vue'
import Pagization from '@/components/common/pagization.vue'
import Table from '@/components/practice/table.vue'
import { showMessage, showStatusMessage } from '@/utils/common/showMessage'
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import axios from 'axios'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ElLoading } from 'element-plus'
import { convertDocxToPreviewApi, getCollegeByClassApi, updateMaterialIsfileApi } from '@/api/baseData'
const route = useRoute()

const userStore = useUserStore()
// **********************筛选表**********************
const formData = ref({
  account: '',
  class: '',
  name: ''
})

// 将状态常量提取出来
const STATUS = {
  PENDING: 0,
  REJECTED: 1,
  APPROVED: 2
}

// 将表单配置提取为常量
const FORM_CONFIG = {
  formModel: [
    {
      prop: 'studentAccount',
      label: '账号',
      type: 'input',
      placeholder: '请输入学生账号'
    },
    {
      prop: 'studentClass',
      label: '班级',
      type: 'input',
      placeholder: '请输入学生班级'
    },
    {
      prop: 'studentName',
      label: '姓名',
      type: 'input',
      placeholder: '请输入学生姓名'
    },
    {
      prop: 'studentMaterialDesc',
      label: '材料名称',
      type: 'input',
      placeholder: '请输入材料名称'
    }
  ],
  btnOpt: [
    {
      name: '查询',
      btnType: 'primary',
      prop: 'query',
      icon: 'Search'
    },
    {
      name: '重置',
      btnType: 'info',
      prop: 'reset',
      icon: 'RefreshRight'
    },
    {
      name: '一键归档',
      btnType: 'success',
      prop: 'onepoint',
      icon: 'onepoint'
    }
  ]
}

/**
 * 点击重置按钮
 */
function reset() {
  getTableData()
  pagizationRef.value.reset()
  selectFormRef.value.reset()
}
//******************* */ 分页先关的***************
const pagizationRef = ref(null)
const selectFormRef = ref(null)
const pagizationToatl = ref(null)
const materialType = ref('intership')
function handleMaterialTypeChange() {
  reset()
  getTableData()
}
/**
 * 获取表格数据
 */
async function getTableData(data) {
  let res = ''
  console.log(materialType.value)

  // 实习按钮获取的数据
  if (materialType.value == 'intership') {
    if (userStore.userInfo.class != '*') {
      res = await getApprovedMaterialsApi({
        ...data,
        studentClass: userStore.userInfo.class,
        status: 2
      })
    } else {
      res = await getApprovedMaterialsApi({
        ...data,
        status: 2
      })
    }
  } else {
    // 就业按钮获取的数据
    if (userStore.userInfo.class != '*') {
      res = await getApprovedEmploymentMaterialsApi({
        ...data,
        studentClass: userStore.userInfo.class,
        status: 2
      })
    } else {
      res = await getApprovedEmploymentMaterialsApi({
        ...data,
        status: 2
      })
    }
  }
  // console.log(res.data)

  if (userStore.userInfo.college !== '*') {
    const collegeData = await getCollegeByClassApi({
      college: userStore.userInfo.college
    })
   
    const collegeAdmin=userStore.userInfo.college
    // console.log(collegeAdmin);
    // 信息工程学院
    // 筛选res.data的数据,判断他们的studentClass班级属于信息工程学院collegeAdmin，学院与班级的对照为collegeData.data
    const filteredData = res.data.filter(item => {
      // 在collegeData.data中查找该学生班级对应的学院
      const classInfo = collegeData.data.find(classItem => classItem.class === item.studentClass);
      console.log(classInfo);
      
      // 如果找到对应的班级信息，且学院匹配，则保留该数据
      return classInfo && classInfo.college === collegeAdmin;
    });
    res.data = filteredData;
    console.log(filteredData)
  }
  
  tableData.value = res.data?.map((item) => {
    return {
      ...item
    }
  })
  pagizationToatl.value = res.total
  showStatusMessage(res)
}
getTableData()

/**
 * 表单按钮点击事件
 * @param type 操作类型
 * @param data 表单数据
 */
function handleForm(type, data) {
  // console.log(type, data)
  switch (type) {
    case 'query':
      query(data)
      break
    case 'output':
      exportToExcel()
      break
    case 'reset':
      reset(data)
      break
    case 'import':
      handleUpload(data)
      break
    case 'submit':
      handleSubmit(data)
      break
      case 'onepoint':
        onepoint(data)
        break
    default:
      break
  }
}

/**
 * 表单查询事件
 * @param {Object} data 查询条件
 */
const queryData = ref(null)
async function query(data) {
  console.log(data)
  getTableData(data)
}

// 列表数据
const tableData = ref([])

// 优化表格列配置
const columns = [
  {
    prop: 'studentAccount',
    label: '账号',
    width: '100'
  },
  {
    prop: 'studentName',
    label: '姓名',
    width: '100'
  },

  {
    prop: 'studentClass',
    label: '班级',
    width: '120'
  },
  {
    prop: 'studentMaterialDesc',
    label: '材料名称',
    width: '120'
  },

  {
    prop: 'studentMaterial',
    label: '附件下载',
    width: '100',
    display: 'button'
  },
  {
    prop: 'materialView',
    label: '附件预览',
    width: '100',
    display: 'button'
  },
  {
    prop: 'status',
    label: '状态',
    width: '100',
    display: 'tag'
  },
  {
    prop: 'isfile',
    label: '是否已入档',
    display: 'tag'

  }
]

// 状态相关的常量和工具函数
const STATUS_CONFIG = {
  [STATUS.PENDING]: {
    text: '待审核',
    type: 'warning'
  },
  [STATUS.REJECTED]: {
    text: '已驳回',
    type: 'danger'
  },
  [STATUS.APPROVED]: {
    text: '已通过',
    type: 'success'
  }
}

const getStatusText = (status) => STATUS_CONFIG[status]?.text || '未知状态'
const getStatusType = (status) => STATUS_CONFIG[status]?.type || 'info'

// 优化操作按钮配置 - 允许二次操作
const options = []

const docPreview = ref('')
const dialogViewVisible = ref(false)
const previewType = ref('') // 用于区分文件类型
const router = useRouter()
// 修改文件预览处理函数
async function handletTableMaterialView(value) {
  router.push({
    path: '/weeklyJournalDetail',
    state: {
      data: JSON.stringify(value.studentMaterial),
      type: 'studentMaterial'
    }
  })
}

// 修改对话框关闭处理函数
function handleDialogViewClose() {
  docPreview.value = ''
  previewType.value = ''
  // 如果是 docx，需要释放创建的 URL
  if (previewType.value === 'docx') {
    URL.revokeObjectURL(docPreview.value)
  }
}

// 材料审核****通过
async function handletTableProcess(data) {
  try {
    const res = await checkStudentNineYeInfoApi({
      id: data.id,
      status: STATUS.APPROVED
    })
    showStatusMessage(res)
    getTableData()
  } catch (error) {
    ElMessage.error('审核失败，请稍后重试')
  }
}

// 材料审核****不通过
async function handletTableNoProcess(data) {
  try {
    const res = await checkStudentNineYeInfoApi({
      id: data.id,
      status: STATUS.REJECTED
    })
    showStatusMessage(res)
    getTableData()
  } catch (error) {
    ElMessage.error('审核失败，请稍后重试')
  }
}

const drawerIsShow = ref(false)
const drawerTitle = ref('')
const drawerData = ref({})
// 查看学生实习周记
function handletTableViewWeekly(data) {
  console.log(data)
  drawerTitle.value = `${data.name}的${data.weekly}实习周记`
  drawerData.value = data
  drawerIsShow.value = true
}
function handleClose() {
  drawerTitle.value = ''
  drawerData.value = {}
  drawerIsShow.value = false
}

// 处理重新审核
async function handleReaudit(data) {
  try {
    const res = await checkStudentNineYeInfoApi({
      id: data.id,
      status: STATUS.PENDING // 重置为待审核状态
    })
    showStatusMessage(res)
    getTableData()
  } catch (error) {
    ElMessage.error('重新审核失败，请稍后重试')
  }
}
async function handleStudentMaterial(data) {
  try {
    const { studentMaterial, studentName, studentMaterialDesc } = data
    const response = await fetch(studentMaterial)

    if (!response.ok) {
      throw new Error('文件下载失败')
    }

    const contentType = response.headers.get('content-type')
    const fileName = `${studentName}的${studentMaterialDesc}`

    downloadFile(studentMaterial, fileName, contentType)
  } catch (error) {
    console.error('下载文件失败:', error)
    ElMessage.error('下载文件失败，请稍后重试')
  }
}

/**
 * 表格的操作事件
 * @param {Object} data  操作行的数据
 * @param {String} type 操作类型-'edit'-'delete'
 */
function handleTable(data, type) {
  console.log(data, type)
  switch (type) {
    case 'materialView':
      handletTableMaterialView(data)
      break
    case 'processs':
      handletTableProcess(data)
      break
    case 'noprocess':
      handletTableNoProcess(data)
      break
    case 'viewWeekly':
      handletTableViewWeekly(data)
      break
    case 'reaudit':
      handleReaudit(data)
      break
    case 'studentMaterial':
      handleStudentMaterial(data)
      break

    default:
      break
  }
}
// 分页器条数发生变化
function handleSizeChange(val) {
  const data = selectFormRef.value.getValue()
  console.log('条数发生变化')
  getTableData({ size: val, ...data })
  pagizationRef.value.reset()
}
// 分页器页数发生变化
function handleCurrentChange(page, size) {
  const data = selectFormRef.value.getValue()
  console.log('页数发生变化')
  getTableData({ page, size, ...data })
}

// 弹窗显示
const dialogTableVisible = ref(false)
const FormJobData = ref({
  studentMaterialDesc: '',
  studentMaterial: ''
})
const formJobOpt = [
  {
    prop: 'studentMaterialDesc',
    label: '实现材料名称',
    type: 'input',
    disabled: true
  },
  {
    prop: 'studentMaterial',
    label: '上传材料',
    type: 'studentMaterial'
  }
]
const btnJobOpt = [
  {
    name: '取消',
    btnType: 'info',
    prop: 'cancel'
  },
  {
    name: '提交',
    btnType: 'primary',
    prop: 'submit'
  }
]

const formJobRef = ref(null)
//dialog关闭前的回调
function handleDialogClose() {
  formJobRef.value.reset()
}

async function handleSubmit(data) {
  console.log(data)
  let info = {
    studentAccount: userStore.userInfo.account,
    studentClass: userStore.userInfo.class,
    studentMaterial: data.studentMaterial,
    studentMaterialDesc: data.studentMaterialDesc
  }

  const res = await uploadStudentInternshipMaterialsApi(info)
  showStatusMessage(res)
  dialogTableVisible.value = false
  getTableData()
  handleDialogClose()
}

// 优化文件下载函数
async function handletTableMaterial(data) {
  if (!data.material) {
    ElMessage.warning('文件不存在')
    return
  }

  const loading = ElLoading.service({
    lock: true,
    text: '准备下载...',
    background: 'rgba(0, 0, 0, 0.7)'
  })

  try {
    const response = await axios({
      url: data.material,
      method: 'GET',
      responseType: 'blob',
      onDownloadProgress: (progressEvent) => {
        const percent = Math.round((progressEvent.loaded * 100) / progressEvent.total)
        loading.setText(`下载进度: ${percent}%`)
      }
    })

    const fileName =
      getFileName(response.headers['content-disposition']) || data.material.split('/').pop()
    downloadFile(response.data, fileName, response.headers['content-type'])

    ElMessage.success('下载成功')
  } catch (error) {
    console.error('Download error:', error)
    ElMessage.error('下载失败，请稍后重试')
  } finally {
    loading.close()
  }
}

// 抽取文件名获取逻辑
function getFileName(disposition) {
  if (!disposition) return null
  const matches = disposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/)
  if (matches && matches[1]) {
    return decodeURIComponent(matches[1].replace(/['"]/g, ''))
  }
  return null
}

// 抽取文件下载逻辑
function downloadFile(data, fileName, type) {
  const blob = new Blob([data], { type })
  const url = window.URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.href = url
  link.download = fileName
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  window.URL.revokeObjectURL(url)
}

// 添加文件大小格式化函数
function formatFileSize(bytes) {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

const selectedRows = ref([])

function selectable(row) {
  console.log(row);
  selectedRows.value.push(row.id)
  // 这里可以根据需要添加选择条件
  // 例如：只允许选择特定状态的行
  return true
}

async function onepoint(){
  if (selectedRows.value.length == 0) {
    showMessage('请选择要归档的行文件','error')
    return 
  }
  // console.log(selectedRows.value);
  console.log(materialType.value);
 const res=await updateMaterialIsfileApi({
    type:materialType.value,
    idarr:selectedRows.value
  })
  showStatusMessage(res)
  getTableData()
  
}
function handleSelectionChange(selection) {
  // selectedRows.value = selection
  // console.log(selectedRows.value);
  console.log(111);
  
}
</script>

<template>
  <div class="material-status-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-wrapper">
        <div class="left-section">
          <h1 class="main-title">材料追踪</h1>
          <div class="sub-title">实习就业管理系统</div>
        </div>
        <div class="right-section">
          <div class="record-count">
            <i class="el-icon-document"></i>
            <span>共 {{ pagizationToatl }} 条记录</span>
          </div>
        </div>
      </div>
    </div>
    <div class="radio-section">
      <el-radio-group v-model="materialType" @change="handleMaterialTypeChange">
        <el-radio-button label="实习材料" value="intership" />
        <el-radio-button label="就业材料" value="employment" />
      </el-radio-group>
    </div>
    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 搜索区域 -->
      <div class="search-section">
        <Form
          :data="formData"
          :formOpt="FORM_CONFIG.formModel"
          :btnOpt="FORM_CONFIG.btnOpt"
          @handleForm="handleForm"
          ref="selectFormRef"
        />
      </div>

      <!-- 表格区域 -->
      <div class="table-section">
        <Table
          :tableData="tableData"
          :columns="columns"
          :options="options"
          @handleTable="handleTable"
          v-loading="loading"
          @selection-change="handleSelectionChange"
        >
          <template #firstColumn>
            <el-table-column 
              type="selection" 
              width="55" 
              :selectable="selectable"
            />
            <el-table-column type="index" label="序号" width="80" align="center" fixed="left" />
          </template>

          <!-- 自定义状态列 -->
          <template #status="{ row }">
            <el-tag :type="getStatusType(row.status)" effect="light" class="status-tag">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </Table>
      </div>

      <!-- 分页区域 -->
      <div class="pagination-section">
        <Pagization
          ref="pagizationRef"
          :total="pagizationToatl"
          :page-sizes="[10, 20, 50, 100]"
          @handleSizeChange="handleSizeChange"
          @handleCurrentChange="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 文件预览对话框 -->
    <el-dialog
      v-model="dialogViewVisible"
      title="文件预览"
      top="5vh"
      width="80%"
      class="preview-dialog"
      @close="handleDialogViewClose"
    >
      <div class="preview-container">
        <template v-if="previewType === 'pdf'">
          <embed :src="docPreview" type="application/pdf" width="100%" height="800" />
        </template>
        <template v-else-if="previewType === 'docx'">
          <iframe :src="docPreview" width="100%" height="800" frameborder="0"></iframe>
        </template>
      </div>
    </el-dialog>

    <!-- 周记抽屉 -->
    <el-drawer
      v-model="drawerIsShow"
      :title="drawerTitle"
      direction="rtl"
      :before-close="handleClose"
      class="weekly-drawer"
      size="50%"
    >
      <div class="weekly-content">
        <div class="weekly-item">
          <div class="weekly-title">
            <i class="el-icon-check"></i>
            本周完成任务
          </div>
          <div class="weekly-text" v-html="drawerData.task"></div>
        </div>
        <div class="weekly-item">
          <div class="weekly-title">
            <i class="el-icon-date"></i>
            下周计划
          </div>
          <div class="weekly-text" v-html="drawerData.plan"></div>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<style lang="scss" scoped>
.material-status-container {
  display: flex;
  flex-direction: column;

  .page-header {
    background: linear-gradient(135deg, #fff 0%, #f6f9fc 100%);
    padding: 24px 32px;
    margin-bottom: 24px;
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);

    .header-wrapper {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .left-section {
        .main-title {
          font-size: 28px;
          font-weight: 600;
          color: #1a1a1a;
          margin: 0 0 8px 0;
          line-height: 1.2;
        }

        .sub-title {
          font-size: 16px;
          color: #666;
          font-weight: 400;
        }
      }

      .right-section {
        .record-count {
          display: flex;
          align-items: center;
          gap: 8px;
          padding: 12px 20px;
          background: #fff;
          border-radius: 8px;
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

          i {
            color: #1890ff;
            font-size: 20px;
          }

          span {
            color: #666;
            font-size: 15px;
            font-weight: 500;
          }
        }
      }
    }
  }
  .radio-section {
    margin-bottom: 20px;
    text-align: right;
  }
}

// 修改状态标签样式
:deep(.el-tag) {
  border-radius: 6px;
  padding: 6px 12px;
  font-weight: 500;
}

:deep(.el-tag--success) {
  background: #f6ffed;
  border-color: #b7eb8f;
  color: #52c41a;
}

:deep(.el-tag--warning) {
  background: #fffbe6;
  border-color: #ffe58f;
  color: #faad14;
}

:deep(.el-tag--danger) {
  background: #fff2f0;
  border-color: #ffccc7;
  color: #ff4d4f;
}

// 表单控件样式
:deep(.el-input) {
  .el-input__wrapper {
    border-radius: 8px;
    transition: all 0.3s ease;

    &:hover {
      box-shadow: 0 0 0 1px #1890ff;
    }

    &.is-focus {
      box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
    }
  }
}

// 对话框样式优化
:deep(.el-dialog) {
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);

  .el-dialog__header {
    background: #fafafa;
    margin: 0;
    padding: 20px 24px;
    border-bottom: 1px solid #f0f0f0;
  }

  .el-dialog__body {
    padding: 24px;
  }
}

// 周记抽屉样式
.weekly-drawer {
  .weekly-content {
    padding: 24px;

    .weekly-item {
      margin-bottom: 32px;
      background: #fafafa;
      border-radius: 8px;
      padding: 20px;

      .weekly-title {
        font-size: 18px;
        font-weight: 600;
        color: #1a1a1a;
        margin-bottom: 16px;
        display: flex;
        align-items: center;
        gap: 8px;

        i {
          color: #1890ff;
          font-size: 20px;
        }
      }

      .weekly-text {
        font-size: 14px;
        line-height: 1.8;
        color: #4a4a4a;
        text-indent: 2em;
      }
    }
  }
}

// 预览对话框样式
.preview-dialog {
  :deep(.el-dialog__header) {
    padding: 20px 24px;
    margin: 0;
    border-bottom: 1px solid #f0f0f0;

    .el-dialog__title {
      font-size: 18px;
      font-weight: 600;
    }
  }

  .preview-container {
    padding: 24px;
    background: #fafafa;
    border-radius: 8px;
    height: 800px;
    overflow: hidden;

    iframe,
    embed {
      border: none;
      width: 100%;
      height: 100%;
      border-radius: 4px;
      background: #fff;
    }
  }
}
</style>
